<?php

namespace app\app\controller;

use app\BaseController;
use app\app\model\UserModel;
use app\app\model\UserRoleModel;
use app\app\model\UserPostModel;

class User extends BaseController
{
    public function list()
    {
        $list = UserModel::field('user_id, dept_id, user_name, nick_name, user_type, email, phonenumber, sex, avatar')
            ->where('del_flag', "0")
            ->select();
        $total = $list->count();
        $list = $list->toArray();
        $index = 0;
        foreach ($list as $key => $value) {
            $index = $index + 1;
            $list[$key]['code'] = $index;
            $role_list = UserRoleModel::alias('a')
                ->field('b.role_name')
                ->where(['a.user_id' => $value['user_id']])
                ->join('sys_role b', 'b.role_id = a.role_id')
                ->select();
            $post_list = UserPostModel::alias('a')
                ->field('c.post_id, c.post_code, c.post_name, c.remark')
                ->where(['user_id' => $value['user_id']])
                ->join('sys_post c', 'a.post_id = c.post_id')
                ->select();
            $list[$key]['role_list'] = $role_list;
            $list[$key]['post_list'] = $post_list;
        }
        $res['list'] = $list;
        $res['rowTotal'] = $total;
        $this->success('success', $res);
    }

    public function editPassword()
    {
        $user_id = input('id', '');
        $old_password = input('oldPassword', '');
        $new_password = input('newPassword', '');
        $user = UserModel::where('user_id', $user_id)->find();
        if (empty($user)) {
            $this->error('户名不存在');
        }
        if ($user['app_password'] != $old_password) {
            $this->error('旧密码错误');
        }
        $user['app_password'] = $new_password;
        $user->save();

        $this->success('success');
    }
}
